package com.kiwilss.aopdemo.ui.room

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.kiwilss.aopdemo.R
import com.kiwilss.aopdemo.ui.room.kotlin.AppDataBase
import com.kiwilss.aopdemo.ui.room.kotlin.User
import com.kiwilss.aopdemo.utils.LogUtils
import kotlinx.android.synthetic.main.activity_room.*

/**
 * @author : Administrator
 * e-mail : kiwilss@163.com
 * time   : 2021/02/02
 *  desc   :
 */
class RoomActivity: AppCompatActivity(R.layout.activity_room) {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val appDataBase = AppDataBase.getInstance(this)

        var user: User
        for (i in 1..10){
            user = User(i,i,"name$i","address$i",false,i)
            appDataBase.userDao().addUser(user)
        }

        btnRoomAdd.setOnClickListener {
            val user = User(11,11,"one","beijing",true)
            appDataBase.userDao().addUser(user)
        }

        btnRoomUpdate.setOnClickListener {
            val user = User(11,11,"11 update","beijing",true)
            appDataBase.userDao().updateUserByUser(user)
        }

        btnRoomQuery.setOnClickListener {
            val userById = appDataBase.userDao().getUserById(1)
            LogUtils.e(userById)
            userById?.run {
                tvRoomTv.text = userById.toString()
            }
        }

        btnRoomDelete.setOnClickListener {
            val user = User(11,11,"11 update", "beijing",true)
            appDataBase.userDao().deleteUserByUser(user)
        }

        btnRoomQueryAll.setOnClickListener {
            val allUser = appDataBase.userDao().getAllUser()
            LogUtils.e(allUser)
            allUser?.run {
                tvRoomTv.text = this.toString()
            }
        }

        btnRoomDeleteSql.setOnClickListener {
            //删除数据库后,再次调用数据库查询方法会报错  android.database.sqlite.SQLiteException: no such table: users (code 1 SQLITE_ERROR):
            // , while compiling: select * from users
            deleteDatabase("user.db")
        }

    }
}